package endpoint

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"

	"gitee.com/hexug/devcloud/mcenter/common/meta"
)

func NewCreateEndpointRequest() *CreateEndpointRequest {
	return &CreateEndpointRequest{}
}

func NewEndpoint(req *CreateEndpointRequest) (*Endpoint, error) {
	data := meta.NewMeta()
	sh := sha1.New()
	if _, err := sh.Write(
		[]byte(
			fmt.Sprintf("%s.%s.%s",
				req.ServiceId,
				req.Method,
				req.Path))); err != nil {
		return nil, err
	}
	data.Id = hex.EncodeToString(sh.Sum(nil))
	return &Endpoint{
		Meta: data,
		Spec: req,
	}, nil
}

func NewRegisterRequest() *RegisterRequest {
	return &RegisterRequest{
		Items: []*CreateEndpointRequest{},
	}
}

func (r *EndpointSet) Add(ep *Endpoint) {
	for _, e := range r.Items {
		if e.Meta.Id == ep.Meta.Id {
			return
		}
	}
	r.Items = append(r.Items, ep)
	r.Total += 1
}

func NewEndpointSet() *EndpointSet {
	return &EndpointSet{
		Items: []*Endpoint{},
	}
}

func NewQueryEndpointRequest() *QueryEndpointRequest {
	return &QueryEndpointRequest{
		PageSize:   5,
		PageNumber: 1,
	}
}

func NewDetailEndpointRequest(id string) *DetailEndpointRequest {
	return &DetailEndpointRequest{
		Id: id,
	}
}
